﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Utility.Helper;

namespace Thksoft.UserCotrols
{
    public partial class CtrlYearEditFunds : BaseControl
    {
        private QX_PLANYEARAPPLYBLL planYearApplyBLL = new QX_PLANYEARAPPLYBLL();
        private Qs_BusinessBLL businessBLL = new Qs_BusinessBLL();
        private Sys_UserBLL userBLL = new Sys_UserBLL();
        private Sys_CompanyBLL companyBLL = new Sys_CompanyBLL();
        private QS_PROJECTBLL projectBLL = new QS_PROJECTBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string busId = Request.QueryString["BusinessId"];
                hidId.Value = busId;
                ViewState["busId"] = busId;
                BindDt(busId);
            }
        }

        #region 旧代码

        //        /// <summary>
        //        /// 绑定数据
        //        /// </summary>
        //        public void BindDt(string busId)
        //        {
        //            var bModel = businessBLL.GetBusinessById(Decimal.Parse(busId));

        //            lblTime.Text = bModel.Business_operator_date.ToShortDateString();

        //            lblUser.Text = userBLL.GetInfoById(bModel.Business_operator_Id.ToString()).USER_NAME;

        //            string sql = string.Format(@"select * from qx_planyearapply t where t.n_business_id=" + busId);

        //            var dtYear = userBLL.Query(sql);

        //            if (dtYear == null || dtYear.Rows.Count < 1)
        //            {
        //                Response.Write("<script>alert('【系统提示】该条数据有误，请与管理员联系');location.href='../Right.aspx';</script>");
        //                return;
        //            }
        //            lblyear.Text = dtYear.Rows[0]["N_YEAR"].ToString();
        //            lblBzyj.Text = dtYear.Rows[0]["C_REAMRK"].ToString();
        //            lbldw.Text = companyBLL.GetInfoById(dtYear.Rows[0]["N_COMPANY_ID"].ToString()).CMY_NAME;
        //            //this.hidId.Value = dtYear.Rows[0]["N_YEARAPP_ID"].ToString() + "@" + busId;
        //            var dt = planYearApplyBLL.GetDataBind(busId);
        //            gvMonthFunds.DataSource = dt;
        //            gvMonthFunds.DataBind();
        //        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            Sum();

            var list = new List<QX_PLANYEAR_DETAIL>();
            for (int i = 0; i < gvMonthFunds.Rows.Count; i++)
            {
                var ydModel = new QX_PLANYEAR_DETAIL();

                string id = ((Label)gvMonthFunds.Rows[i].Cells[0].FindControl("lblId")).Text;

                string xmmc = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("txtProjectName")).Text;

                string je = ((TextBox)gvMonthFunds.Rows[i].Cells[2].FindControl("txtNowMonth")).Text;
                string aa = "";
                if (je != "" && je != null)
                {
                    aa = FormulaCalculator.Eval(je).ToString();
                }

                string bz = ((TextBox)gvMonthFunds.Rows[i].Cells[3].FindControl("txtremark")).Text;
                ydModel.N_YDETAIL_ID = decimal.Parse(id);
                ydModel.N_AMOUNT = je == "" ? 0 : decimal.Parse(je);
                ydModel.C_REMARK = bz;
                ydModel.N_OPERATORID = lognUser.USER_ID;

                list.Add(ydModel);
            }

            int count = planYearApplyBLL.Updates(list, lognUser.USER_NAME);
            if (count == 0)
            {
                MessageBox.Show(Page, "修改失败！");
            }
        }

        //        protected void gvMonthFunds_RowDataBound(object sender, GridViewRowEventArgs e)
        //        {
        //            if (e.Row.RowType == DataControlRowType.DataRow)
        //            {
        //                string type = ((Label)e.Row.FindControl("lbltype")).Text;
        //                if (type == "0")
        //                {
        //                    e.Row.Attributes["style"] = "background-color:#B2D8FF;font-size: 14px";

        //                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
        //                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

        //                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
        //                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;

        //                    // e.Row.Cells[2].Attributes["style"] = "font-size: 14px";
        //                }
        //                else if (type == "1")
        //                {
        //                    e.Row.Attributes["style"] = "background-color:#CCCCCC;font-size: 13px;";

        //                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
        //                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

        //                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
        //                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;

        //                    //  e.Row.Cells[2].Attributes["style"] = "font-size: 13px";
        //                }

        //            }
        //        }

        #region 求和 方法

        /// <summary>
        /// 求和
        /// </summary>
        private void Sum()
        {
            #region for循环求和

            DataTable dt = (DataTable)gvMonthFunds.DataSource;

            for (int i = 0; i < gvMonthFunds.Rows.Count; i++)
            {
                //0 主节点  1分节点  2子节点（可录入数据）
                string type = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("lbltype")).Text;
                string pid = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("lblProID")).Text;
                if (type != "2")
                {
                    //求和
                    decimal heje = 0;
                    //该节点下所有子节点
                    DataTable dtchild = projectBLL.SelectFor(" and  d.n_type = 2 ", pid, lognUser.USER_NAME);

                    for (int j = 0; j < dtchild.Rows.Count; j++)
                    {
                        for (int k = 0; k < gvMonthFunds.Rows.Count; k++)
                        {
                            string type2 = ((Label)gvMonthFunds.Rows[k].Cells[1].FindControl("lbltype")).Text;

                            string pid2 = ((Label)gvMonthFunds.Rows[k].Cells[1].FindControl("lblProID")).Text;

                            //每个文本框求和
                            string je = ((TextBox)gvMonthFunds.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim();
                            string a = "";
                            if (je != "" && je != null)
                            {
                                a = FormulaCalculator.Eval(je).ToString();
                            }

                            if (type2 == "2" && dtchild.Rows[j]["n_proid"].ToString() == pid2)
                            {
                                heje += Convert.ToDecimal(a == "" ? "0" : a);
                                //heje += Convert.ToDecimal(((TextBox)gvMonthFunds.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim() == "" ? "0" : ((TextBox)gvMonthFunds.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim());
                            }
                        }
                    }

                    ((Label)gvMonthFunds.Rows[i].Cells[2].FindControl("lblMonthjh")).Text = heje.ToString();
                    ((TextBox)gvMonthFunds.Rows[i].Cells[2].FindControl("txtNowMonth")).Text = heje.ToString();
                }
                else
                {
                }
            }

            #endregion for循环求和
        }

        #endregion 求和 方法

        protected void btnEdtSum_Click(object sender, EventArgs e)
        {
            Sum();
        }

        /// <summary>
        /// 打印事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PrintClick(object sender, EventArgs e)
        {
            try
            {
                decimal id = Convert.ToDecimal(ViewState["busId"]);
                var entity = new QX_PLANYEARAPPLYBLL().FindByBuid(id);
                //var user = userBLL.GetInfoById(entity.N_USER_ID.ToString());
                Session["YEAREDITFUNDSHeader"] = entity.N_YEAR + "年计划申请";
                var sql = @"SELECT
	T1.N_YDETAIL_ID AS 详情编号,
	T1.N_PROID AS 项目编号,
	T1.C_PRONAME AS 项目名称,
	T1.N_AMOUNT AS 申请金额,
	DECODE(T1.N_TYPE,0,'主节点',1,'分节点',2,'子节点（可录入数据）','其它') AS 节点类型,
	T1.C_REMARK AS 备注
FROM QX_PLANYEAR_DETAIL T1
LEFT JOIN QS_BUSINESS T2
ON T1.N_BUSINESS_ID = T2.N_BUSINESS_ID
WHERE T1.N_BUSINESS_ID = {0}
ORDER BY T1.N_PROID
";
                sql = string.Format(sql, id);
                var dt = new QX_PLANYEARAPPLYBLL().Query(sql);
                Session["YEAREDITFUNDSBody"] = dt;
                MessageBox.ResponseScript(Page, "top.MessageBox.Print({Value:\"ID=BASIC&VALUE=YEAREDITFUNDS\",Area:[\"800px\",\"500px\"],Scrollbar:true})");
            }
            catch (Exception)
            {
                MessageBox.Show(Page, "打印异常");
            }
        }

        #endregion 旧代码

        #region 新代码

        public void BindDt(string busId)
        {
            QS_Business bModel = new Qs_BusinessBLL().GetBusinessById(Decimal.Parse(busId));

            lblTime.Text = bModel.Business_operator_date.DateFormat("yyyy-MM-dd");

            lblUser.Text = new Sys_UserBLL().GetInfoById(bModel.Business_operator_Id.ToString()).USER_NAME;

            string sql = string.Format(@" select * from qx_planyearapply t where t.n_business_id=" + busId);

            DataTable dtYear = new BaseBLL().Query(sql);

            if (dtYear == null || dtYear.Rows.Count < 1)
            {
                Response.Write("<script>alert('【系统提示】该条数据有误，请与管理员联系');location.href='../Right.aspx';</script>");
                return;
            }

            lblyear.Text = dtYear.Rows[0]["N_YEAR"].ToString();

            lblBzyj.Text = dtYear.Rows[0]["C_REAMRK"].ToString();

            lbldw.Text = new Sys_CompanyBLL().GetInfoById(dtYear.Rows[0]["N_COMPANY_ID"].ToString()).CMY_NAME;

            this.hidId.Value = dtYear.Rows[0]["N_YEARAPP_ID"].ToString() + "@" + busId;

            DataTable dt = new QX_PLANYEARAPPLYBLL().GetDataBind(busId);

            gvMonthFunds.DataSource = dt;

            gvMonthFunds.DataBind();
        }

        protected void gvMonthFunds_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string type = ((Label)e.Row.FindControl("lbltype")).Text;
                if (type == "0")
                {
                    e.Row.Attributes["style"] = "background-color:#B2D8FF;font-size: 14px";

                    // e.Row.Cells[2].Attributes["style"] = "font-size: 14px";
                }
                else if (type == "1")
                {
                    e.Row.Attributes["style"] = "background-color:#CCCCCC;font-size: 13px;";

                    //  e.Row.Cells[2].Attributes["style"] = "font-size: 13px";
                }
            }
        }

        #endregion 新代码
    }
}